<template>
  <div class="app-container xjAdd">
    <el-form :model="formParams" :rules="rules" ref="formParams" label-width="120px" class="demo-formParams">
      <el-card class="margin-bottom-15">
        <el-descriptions title="设备基本信息" :column="3" border></el-descriptions>
        <el-row>
          <el-col :span="6">
            <el-form-item label="设备序列号" prop="sn">
              <el-input v-model="formParams.sn" placeholder="请输入设备序列号" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="设备名称" prop="name">
              <el-input v-model="formParams.name" placeholder="请输入设备名称" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="从机号" prop="slaveId">
              <el-input v-model="formParams.slaveId" placeholder="请输入从机号" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="设备类型" prop="type">
              <el-select v-model="formParams.type" placeholder="请选择设备类型">
                <el-option v-for="dict in dict.type.device_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col  :span="6">
            <el-form-item label="所属部门" prop="deptId">
              <treeselect v-model="formParams.deptId" :options="deptOptions" :show-count="true" placeholder="请选择归属部门"/>
            </el-form-item>
            <!-- <el-form-item label="所属街道id" prop="deptId">
              <el-input v-model="formParams.deptId" placeholder="请输入所属街道id" />
            </el-form-item> -->
          </el-col>
          <el-col  :span="6">
            <el-form-item label="通讯间隔" prop="timeSpace">
              <el-input v-model="formParams.timeSpace" placeholder="请输入通讯间隔" />
            </el-form-item>
          </el-col>
          <el-col  :span="6">
            <el-form-item label="经度" prop="lng">
              <el-input v-model="formParams.lng" placeholder="请输入经度" />
            </el-form-item>
          </el-col>
          <el-col  :span="6">
            <el-form-item label="纬度" prop="lat">
              <el-input v-model="formParams.lat" placeholder="请输入纬度" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col  :span="24">
            <el-form-item label="备注" prop="bz">
              <el-input v-model="formParams.bz" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-card>
      <el-form-item style="text-align: center; margin-left: 0">
        <el-button type="primary" @click="submitForm()">提交</el-button>
      </el-form-item>
      <el-card class="margin-bottom-15">
        <el-descriptions title="选择设备定位" :column="3" border></el-descriptions>
        <div id="container"></div>
      </el-card>

      
    </el-form>

    

  </div>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader';
import { listDeviceInfo, getDeviceInfo, delDeviceInfo, addDeviceInfo, updateDeviceInfo } from "@/api/wrj/deviceInfo";
import { treeselect } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: 'add',
  dicts: ['device_type'],
  components: { Treeselect },
  // dicts: ['ptsj_score_plus', 'ptsj_score_redution', 'ptsj_red_card_item', 'ptsj_yellow_card_item', 'ptsj_blue_card_item'],
  data() {
    return {
      deptOptions:null,
      formParams: {
        lat:'',
        lng:'',
        zz: '',
        fzz: '',
        groupList: [],
      },
      id:'',
      // 手动打点坐标
      newLocationMarker:null,
      rules: {
        roomProblem: [
          { required: true, message: '请输入存在的问题', trigger: 'blur' },
        ]
      },
      
    }
  },
  created() {
    if(this.$route.query.id){
      this.id = this.$route.query.id
    }
    this.getTreeselect();
    
  },
  mounted(){
    this.$nextTick(()=>{
        this.initAMap();
        
    })
  },
  unmounted() {
    this.map?.destroy();
  },
  methods: {
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data;
      });
    },
    // 获取详情信息
    getDeviceInfo(id){
      getDeviceInfo(id).then(res=>{
        this.formParams = res.data;
        let lng = this.formParams.lng;
        let lat = this.formParams.lat;
        console.log(lng)
        var marker = new AMap.Marker({
              icon: "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-red.png",
              position: [lng, lat],
              offset: new AMap.Pixel(-13, -30),
            });
            this.map.add(marker);
      })
    },

    submitForm() {
      this.$refs["formParams"].validate(valid => {
        if (valid) {
          if (this.formParams.id != null) {
            updateDeviceInfo(this.formParams).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDeviceInfo(this.formParams).then(response => {
              this.$modal.msgSuccess("新增成功");
              // this.open = false;
              // this.getList();
            });
          }
        }else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 清空数据
    clearFormParams() {
      this.formParams = {
        zz: '',
        fzz: '',
      },
      this.groupList = []
    },
    // 地图初始化
    initAMap() {
      window._AMapSecurityConfig = {
        securityJsCode: "ea203d3756bb886bcdd4833c10c332b9",
      };
      AMapLoader.load({
        key: "475db83acfc1af0cbab24fbdaa34072c", // 申请好的Web端开发者Key，首次调用 load 时必填
        version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
        plugins: ["AMap.Scale"], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
      })
        .then((AMap) => {
          let that = this;
          this.defaultLayer = new AMap.createDefaultLayer()
          // this.satelliteLayer = new AMap.TileLayer.Satellite();
          this.map = new AMap.Map("container", {
            // 设置地图容器id
            viewMode: "3D", // 是否为3D地图模式
            zoom: 11, // 初始化地图级别
            center: [120.577490, 29.932739], // 初始化地图中心点位置
            // layers: [this.satelliteLayer],
          });
          this.map.on('click', that.showInfoClick);

          if(this.id){
            this.getDeviceInfo(this.id);
          }
          
          // this.$nextTick(()=>{
            
          // })
          
        })
        .catch((e) => {
          console.log(e);
        });
        
    },
    showInfoClick(e){
      if(this.newLocationMarker!=null){
        this.map.remove(this.newLocationMarker);
      }

      this.formParams.lng = e.lnglat.getLng()
      this.formParams.lat = e.lnglat.getLat()
      // var text = '您在 [ '+e.lnglat.getLng()+','+e.lnglat.getLat()+' ] 的位置单击了地图！'
      var marker = new AMap.Marker({
              icon: "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
              position: [e.lnglat.getLng(), e.lnglat.getLat()],
              offset: new AMap.Pixel(-13, -30),
            });
      this.newLocationMarker = marker
      this.map.add(this.newLocationMarker);
    }
  }
}
</script>

<style lang="scss" scoped>
.margin-bottom-15 {
  margin-bottom: 10px;
  // margin-bottom: 50px;
}
</style>

<style>
#container{
        padding:0px;
        margin: 0px;
        width: 100%;
        height: 100vh;
    }
.amap-icon img {
        width: 25px;
        height: 34px;
    }
</style>
